﻿using System;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using Outlook.WorkItems.Extension.Manager.TeamProjectManager;

namespace Outlook.WorkItems.Extension.Addin.Forms
{
    public partial class SaveMappingForm : Form
    {
        private WorkItemMapping _workItemMapping;

        public SaveMappingForm()
        {
            InitializeComponent();
        }

        public SaveMappingForm(WorkItemMapping workItemMapping)
            :this()
        {
            _workItemMapping = workItemMapping;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            _workItemMapping.Name = txtMappingName.Text;
            var element = _workItemMapping.SerializeWorkItemMapping();
            XDocument xdoc;

            var filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\OWIPlugin\\WorkItemMapping.owi";

            XElement rootElement;
            if (File.Exists(filePath))
            {
                xdoc = XDocument.Load(filePath);
                rootElement = xdoc.Element("WorkItemMappings");
            }
            else
            {
                rootElement = new XElement("WorkItemMappings");
                xdoc = new XDocument(rootElement);
            }
            
            if (rootElement != null) 
                rootElement.Add(element);

            xdoc.Save(filePath);
        }
    }
}
